const express = require('express');
const router = express.Router();
const User = require('../models/user');
const  crypto = require('crypto');


router.post('/register',function(req,res){
	
	var name = req.body.name;
	User.findOne({name:name}).exec(function(err,data){
		if(err){
			return res.json({error:1,msg:'错误'});
		}
		if(data){
		   return res.json({error:1,msg:'用户已存在'});
		   
		}
		
		var md5 = crypto.createHash('md5');
		var password = md5.update(req.body.password).digest('hex');
		var user = new User({
			name:req.body.name,
			password:password,
			phone:req.body.phone,
			time:new Date()
		});
		user.save(function(err){
		if(err){
			return res.json({error:1,msg:'错误'});
		}
		 res.json({error:0,msg:'成功'});
		
		})
	})
	
		
})
//登录
router.post('/login',function(req,res){
//	console.log(req.body);
	var name = req.body.name;
	
	User.findOne({name:name}).exec(function(err,data){

		if(err){
			return res.json({error:1,msg:'错误'});
		}
		if(!data){
		   return res.json({error:1,msg:'用户不存在'});
		}
		var md5 = crypto.createHash('md5');
		var password = md5.update(req.body.password).digest('hex');
		if(data.password != password){
			return res.json({error:1,msg:'密码错误'});
		}
		res.cookie("userId",data._id,{
                    path:'/',
                    maxAge:1000*60*60*24
                });
        res.cookie("name",data.name,{
                    path:'/',
                    maxAge:1000*60*60*24
                });
//              req.session.users = data;
//              console.log(req.session.users);
		res.json({error:0,msg:'登录成功',result:{name:data.name}});
		
	})
})
//退出
router.post("/logout", function (req,res,next) {
    res.cookie("userId","",{
        path:"/",
        maxAge:-1
    });
    res.json({
        error:"0",
        msg:'',
        result:''
    })
});

router.get("/checkLogin", function (req,res,next) {
    if(req.cookies.userId){
        res.json({
            error:'0',
            msg:'',
            result:req.cookies.name || ''
        });
    }else{
        res.json({
            error:'1',
            msg:'未登录',
            result:''
        });
    }
});
router.post('/myself',function(req,res){
	var id = req.cookies.userId;
	console.log(id);
	User.findById(id).exec(function(err,data){
		
		if(err){
			return res.json({error:1,msg:'错误'});
		}
		res.json({error:0,msg:'成功',result:{data}})
	})
})

//添加地址
router.post('/setaddress', function(req, res, next) {
	console.log(req.body);
	var userId = req.cookies.userId;
	console.log(userId);
	User.findById(userId).exec(function(err, data) {
		if(err) {
			res.json({
				error: 1,
				message: '系统错误'
			})
		}
		data.address.push(req.body);
		data.save(function(err, address) {
			if(err) {
				res.json({
					error: 2,
					message: '成功',
				})
				res.json({error:3,message:'成功',data: address})
			}
		})
	})
})

//
router.post('/getaddress',function(req,res,next){
	var userId = req.cookies.userId;
	User.findById(userId).exec(function(err, data) {
		if(err) {
			res.json({
				error: 1,
				message: '系统错误'
			})
		}
		res.json({error:0,msg:'成功',data})
	})
})
//
router.post('/deladdress',function(req,res,next){
	var userId = req.cookies.userId;
	User.findById(userId).exec(function(err, data) {
//		console.log(data.address)
		if(err) {
			res.json({
				error: 1,
				message: '系统错误'
			})
		}
		data.address.splice(1,1)
		data.save();
		res.json({error:0,msg:'成功',data})
	})
})
//关注商品
router.post('/guanzhu',function(req,res){
	var shops = req.body.shop;
//	console.log(shops)
	var id = req.cookies.userId;
	var shopId = shops._id;
	User.findById(id).exec(function(err,data){
		if(err) {
			return res.json({
				error: 1,
				message: '系统错误'
			})
		}
		
		if(data){
			var shopItem = '';
			data.guanzhu.forEach(function(item){
				console.log(item)
				if(shopId == item._id){
					shopItem = item;
				}
			})
			if(shopItem){
				var guanzhu = new User(data);
				guanzhu.save(function(err2, doc2) {
					if(err2) {
						res.json({
							error: 1,
							message: '系统错误'
						})
					} else {
						res.json({
							error: 0,
							message: '成功'
						})
					}
				})

			}else{
				data.guanzhu.push(shops);
				data.save();
				res.json({error:0,msg:'成功',result:{data}});
			}
			
		}
//		
//		
//		
	})
})
//取消关注
router.post('/quxiaoguanzhu',function(req,res){
	var shops = req.body.shop;
//	console.log(shops)
	var id = req.cookies.userId;
	var shopId = shops._id;

	User.findById(id).exec(function(err,data){
		if(err) {
			return res.json({
				error: 1,
				message: '系统错误'
			})
		}
		
		data.guanzhu.forEach(function(item,ins){
			if(shopId == item._id) {
			data.guanzhu.splice(ins,1)	
			data.save()
			}
			
		})

	})
})
//获取关注商品
router.post('/getguanzhu',function(req,res){
	var id = req.cookies.userId;
	User.findById(id).exec(function(err,data){
		if(err) {
			return res.json({
				error: 1,
				message: '系统错误'
			})
		}
		res.json({error:0,msg:'成功',result:{data}})
	})
})

module.exports= router;